package com.zzf.design.template;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 模版模式
 * @author zzf
 * @date 2018/8/26 22:24.
 */
public class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    //方法封装
    private Connection getConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    private PreparedStatement createPreparedStatment(Connection con, String sql) throws SQLException {
        return con.prepareStatement(sql);
    }

    private ResultSet executeQuery(PreparedStatement stmt, Object[] values) throws SQLException {
        for (int i = 0; i < values.length; i++) {

            stmt.setObject(i, values[i]);
        }
        return stmt.executeQuery();
    }

    private void closeStatment(Statement stmt) throws SQLException {
        stmt.close();
    }

    private void closeResult(ResultSet rs) throws SQLException {
        rs.close();
    }

    private void closeConnection(Connection con) throws SQLException {
        con.close();
    }


    private List<?> parseResultSet(ResultSet rs, RowMapper rowMapper) throws Exception {
        List result = new ArrayList();
        int rowNum = 1;
        while (rs.next()) {

            result.add(rowMapper.mapRow(rs, rowNum++));
        }
        return result;
    }


    public List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object[] values) throws Exception {

        //1、获取链接
        Connection connection = getConnection();//dataSource.getConnection();

        //2、创建语句集
        PreparedStatement pstmt = createPreparedStatment(connection, sql);//connection.prepareStatement(sql);

        //3、执行语句集、并且获得结果集
        ResultSet rs = executeQuery(pstmt, null);//pstmt.executeQuery();

        //4、解析语句集
        List<?> result = parseResultSet(rs, rowMapper);
//        List result = new ArrayList();
//        int rowNum = 1;
//        while (rs.next()) {
//
//            result.add(processResult(rs, rowNum));
//        }

        //5、关闭结果集
        this.closeStatment(pstmt);
        //6、关闭语句集
        this.closeResult(rs);
        //7、关闭链接
        this.closeConnection(connection);

        return result;
    }

//    public abstract Object processResult(ResultSet rs, int rowNum) throws SQLException;
}
